package com.pangolin.pangolinim.service.thread;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Base64;
import android.util.Log;

import com.orhanobut.logger.Logger;
import com.pangolin.pangolinim.app.BroadcastMsg;
import com.pangolin.pangolinim.app.mainApp;
import com.pangolin.pangolinim.net.NetFormat;
import com.pangolin.pangolinim.net.Netpackage;
import com.pangolin.pangolinim.service.list.ContactList;
import com.pangolin.pangolinim.service.list.MessageList;
import com.pangolin.pangolinim.service.system.AppRuntime;
import com.pangolin.pangolinim.service.thread.base.baseThread;
import com.pangolin.pangolinim.sqlite.DBContact;
import com.pangolin.pangolinim.sqlite.DBMessage;
import com.pangolin.pangolinim.sqlite.DBSession;
import com.pangolin.pangolinim.sqlite.DBUser;
import com.pangolin.pangolinim.utils.AESUtil;
import com.pangolin.pangolinim.utils.BundleUtil;
import com.pangolin.pangolinim.utils.DBHelperUtil;
import com.pangolin.pangolinim.utils.DHUtil;
import com.pangolin.pangolinim.utils.DateUtil;
import com.pangolin.pangolinim.utils.FileUtil;
import com.pangolin.pangolinim.utils.GsonUtil;
import com.pangolin.pangolinim.utils.SPUtil;

import org.json.JSONException;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class sendThread extends baseThread {
    private Handler handler;

    @Override
    public void run() {
        if(mSocket == null || !mSocket.isconnect()){
            Logger.e("sendThread:run:socket error");
            //TODO:将错误信息返回给上层UI
            BundleUtil bundleUtil = new BundleUtil(BroadcastMsg.SIG_CORE_NETERR , "network error");
            BroadcastSender(bundleUtil.getBundle());
            return;
        }

        Logger.d("sendThread:run:sendThread started");
        Looper.prepare();  // 初始化异步线程的消息循环队列
        if (handler == null) {
            synchronized (sendThread.class) { // 线程间安全
                // 创建消息队列接受activity发送给服务器的消息
                handler = new Handler(Looper.myLooper(), new Handler.Callback() {
                    @Override
                    public boolean handleMessage(Message msg) {
                        if(msg.what == BroadcastMsg.SIG_UI_STOP){   //停止信号
                            Looper.myLooper().quitSafely();
                        }else if(msg.what == BroadcastMsg.SIG_UI_DATA){  //操作信号
                            Map<String , Object> resMap = (Map<String , Object>)msg.obj;
                            /** 分发处理各种消息类型 */
                            try{
                                switch ((int) resMap.get("type")){
                                    case BroadcastMsg.SIG_UI_STOP:          //安全退出循环
                                        Looper.myLooper().quitSafely();
                                        break;
                                    case BroadcastMsg.DATA_UI_REG:          //注册用户
                                        NetRegister(resMap);
                                        break;
                                    case BroadcastMsg.DATA_UI_LOGIN:        //用户登陆
                                        NetLogin(resMap);
                                        break;
                                    case BroadcastMsg.DATA_UI_LOGOUT:       //用户退出登陆
                                        NetLogout(resMap);
                                        break;
                                    case BroadcastMsg.DATA_UI_FINDUSER:     //搜索用户
                                        NetFindUser(resMap);
                                        break;
                                    case BroadcastMsg.DATA_UI_REPASS:       //修改密码
                                        NetRepass(resMap);
                                        break;
                                    case BroadcastMsg.DATA_UI_REINFO:       //修改用户信息
                                        NetReinfo(resMap);
                                        break;
                                    case BroadcastMsg.DATA_UI_SENDMSG:      //发送消息
                                        NetSendMsg(resMap);
                                        break;
                                    case BroadcastMsg.DATA_UI_CONFIRM:      //确认添加好友
                                        NetConfirmFriend(resMap);
                                        break;
                                    case BroadcastMsg.DATA_UI_OPERATE:      //添加好友
                                        NetOperateFriend(resMap);
                                        break;
                                    case BroadcastMsg.DATA_UI_DELETE:       //删除好友
                                        NetDeleteFriend(resMap);
                                        break;
                                    case BroadcastMsg.DATA_UI_CONTACTS:     //获取联系人列表
                                        NetFriendList(resMap);
                                        break;
                                    case BroadcastMsg.DATA_UI_OFFMSG:       //获取离线消息
                                        NetOffMessage(resMap);
                                        break;
                                    case BroadcastMsg.DATA_UI_SESSIONS:     //最近会话
                                        DataSessions(resMap);
                                        break;
                                    case BroadcastMsg.DATA_UI_MYINFO:       //获取个人信息
                                        DataMyinfo(resMap);
                                        break;
                                    case BroadcastMsg.DATA_UI_DOWNPIC:      //下载图片
                                        NetDownpic(resMap);
                                        break;
                                    case BroadcastMsg.DATA_UI_UPLOADPIC:    //上传图片
                                        NetUploadpic(resMap);
                                        break;
                                    case BroadcastMsg.DATA_UI_NEWFRIEND:    //新的朋友申请列表
                                        DataNewFriend(resMap);
                                        break;
                                    case BroadcastMsg.DATA_UI_GETMSG:       //获取聊天记录
                                        DataMessages(resMap);
                                        break;
                                    case BroadcastMsg.DATA_UI_SETSESSION:   //更新会话信息
                                        DataUpdateSession(resMap);
                                        break;
                                    case BroadcastMsg.DATA_UI_DELLOG:       //删除聊天记录
                                        DataDeleteMsg(resMap);
                                        break;
                                    case BroadcastMsg.DATA_UI_GETCONFIG:    //获取系统设置
                                        DataGetConfig(resMap);
                                        break;
                                    case BroadcastMsg.DATA_UI_SETCONFIG:    //修改系统设置
                                        DataSetConfig(resMap);
                                        break;
                                }
                            }catch (IOException ex){
                                BundleUtil bundleUtil = new BundleUtil(BroadcastMsg.SIG_CORE_NETERR ,  ex.getMessage());
                                BroadcastSender(bundleUtil.getBundle());
                            }catch (Exception ex){
                                BundleUtil bundleUtil = new BundleUtil(BroadcastMsg.SIG_CORE_SYSERR ,  ex.getMessage());
                                BroadcastSender(bundleUtil.getBundle());
                            }
                        }
                        return true;
                    }
                });
                // 释放锁
                sendThread.class.notifyAll();
            }
        }
        Looper.loop();
        Logger.d("sendThread:run:sendThread stoped");
    }

    public Handler getHandler() {
        if (handler == null) {
            synchronized (sendThread.class) {  // 线程间安全
                if (handler == null) {
                    try {
                        sendThread.class.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    return handler;
                } else {
                    return handler;
                }
            }
        } else {
            return handler;
        }
    }

    /** *********************************   以下是各类消息的功能函数   *********************************/

    //网络请求 注册用户
    private void NetRegister(Map<String , Object> resMap) throws Exception{
        Netpackage pkg = NetFormat.registerEncode((String)resMap.get("username") , (String)resMap.get("passwd"));
        _sendPackage(pkg);
    }

    //网络请求 用户登陆
    private void NetLogin(Map<String , Object> resMap) throws Exception{
        Netpackage pkg = NetFormat.loginEncode((int)resMap.get("uid") , (String)resMap.get("passwd") , 1);
        _sendPackage(pkg);
    }

    //网络请求 用户退出登陆
    private void NetLogout(Map<String , Object> resMap) throws Exception{
        Netpackage pkg = NetFormat.logoutEncode(mUid , mKey );
        _sendPackage(pkg);
    }

    //网络请求 搜索用户
    private void NetFindUser(Map<String , Object> resMap) throws Exception{
        Netpackage pkg = NetFormat.findFriendEncode(mUid ,(int)resMap.get("friend_uid"), mKey );
        _sendPackage(pkg);
    }

    //网络请求 修改密码
    private void NetRepass(Map<String , Object> resMap) throws Exception{
        Netpackage pkg = NetFormat.repassEncode(mUid ,(String)resMap.get("newpasswd"), mKey );
        _sendPackage(pkg);
    }

    //网络请求 修改用户信息
    private void NetReinfo(Map<String , Object> resMap) throws Exception{
        Netpackage pkg = NetFormat.setUserinfoEncode(mUid ,(String)resMap.get("username"),(String)resMap.get("headimg"), mKey );
        usernameTmp = (String)resMap.get("username");
        headimgTmp = (String)resMap.get("headimg");
        _sendPackage(pkg);
    }

    //网络请求 发送消息
    private void NetSendMsg(Map<String , Object> resMap) throws Exception{
        Date date = new Date();
        int timestamp = (int)(date.getTime() / 1000);
        DBContact contact = contacts.get_onecontact((int)resMap.get("uid"));
        if(contact == null){
            BundleUtil bundleUtil = new BundleUtil(BroadcastMsg.SIG_CORE_SYSERR , "发送消息：获取联系人加密密钥错误");
            BroadcastSender(bundleUtil.getBundle());
            return;
        }
        String encryptMsg = AESUtil.encrypt((String)resMap.get("msgtext") , contact.getSeckey());
        Netpackage pkg = NetFormat.messageEncode(
                (String)resMap.get("mid") ,
                (int)resMap.get("msg_type") ,
                mUid ,
                (int)resMap.get("uid") ,
                mKey ,
                encryptMsg,
                timestamp );
        //插入数据库chat_msg表
        DBMessage msg = new DBMessage();
        msg.setMid((String)resMap.get("mid"));
        msg.setUid((int)resMap.get("uid"));
        msg.setType((int)resMap.get("msg_type"));
        msg.setIo(1);
        msg.setStatus(1);
        msg.setMsgtext((String)resMap.get("msgtext"));
        msg.setTimestamp(timestamp);
        DBHelperUtil.getInstance().insert_msg(msg);
        //更新会话列表chat_session表
        DBSession session = new DBSession();
        session.setLastmsg(msg.getMsgtext());
        session.setMsgtype(msg.getType());
        session.setUid(contact.getUid());
        session.setName(contact.getName());
        session.setHeadimg(contact.getHeadimg());
        session.setLasttime(DateUtil.getWechatTime(msg.getTimestamp() * 1000l));
        session.setUnread(0);
        sessions.insert_session(session);
        DBHelperUtil.getInstance().insert_session(session);
        _sendPackage(pkg);
    }

    //网络请求 接受好友请求
    private void NetConfirmFriend(Map<String , Object> resMap) throws Exception{
        //获得自己公钥私钥对，并计算对称密钥，并修改数据库
        if((int)resMap.get("result") == 1){
            DBUser user = DBHelperUtil.getInstance().get_oneuser((int)resMap.get("uid"));
            if(user == null){
                BundleUtil bundleUtil = new BundleUtil(BroadcastMsg.SIG_CORE_SYSERR , "好友申请处理：未找到该申请记录");
                BroadcastSender(bundleUtil.getBundle());
                return;
            }
            byte publicKeyB[] = Base64.decode(user.getPubkeyb().getBytes(), Base64.NO_WRAP);
            Map<String, Object> keyMapA = DHUtil.initKey(publicKeyB);
            byte pubKeyAbit[] = DHUtil.getPublicKey(keyMapA);
            byte priKeyAbit[] = DHUtil.getPrivateKey(keyMapA);
            byte seckeybit[] = DHUtil.getSecretKey(publicKeyB, priKeyAbit);
            String pubkeya = Base64.encodeToString(pubKeyAbit , Base64.NO_WRAP);
            String prikeya = Base64.encodeToString(priKeyAbit , Base64.NO_WRAP);
            String seckey = Base64.encodeToString(seckeybit , Base64.NO_WRAP);
            //同步user表
            user.setPubkeya(pubkeya);
            user.setPrikeya(prikeya);
            user.setSeckey(seckey);
            user.setType(5);
            DBHelperUtil.getInstance().update_user(user);
            //同步contacts列表
            DBContact contact = new DBContact();
            contact.setUid(user.getUid());
            contact.setName(user.getName());
            contact.setHeadimg(user.getHeadimg());
            contact.setSeckey(user.getSeckey());
            contacts.insert_contact(contact);
            //返回封包
            Netpackage pkg = NetFormat.confirmFriendEncode(
                    mUid ,
                    (int)resMap.get("uid") ,
                    (int)resMap.get("result") ,
                    mKey ,
                    pubkeya);
            _sendPackage(pkg);
        }else{
            DBUser user = new DBUser();
            user.setUid((int)resMap.get("uid"));
            user.setType(4);
            DBHelperUtil.getInstance().update_user(user);
            return;
        }
    }

    //网络请求 添加好友
    private void NetOperateFriend(Map<String , Object> resMap) throws Exception{
        //获得自己公钥私钥对
        String pubkeya = mainApp.getPubkey();
        String prikeya = mainApp.getPrikey();
        Netpackage pkg = NetFormat.operateFriendEncode(
                mUid ,
                (int)resMap.get("uid") ,
                mKey ,
                (String)resMap.get("context") ,
                pubkeya);
        //插入数据库
        DBUser user = new DBUser();
        user.setUid((int)resMap.get("uid"));
        user.setPubkeya(pubkeya);
        user.setPrikeya(prikeya);
        user.setName((String)resMap.get("name"));
        user.setHeadimg((String)resMap.get("headimg"));
        user.setType(1);
        DBHelperUtil.getInstance().insert_user(user);
        _sendPackage(pkg);
    }

    //网络请求 删除好友
    private void NetDeleteFriend(Map<String , Object> resMap) throws Exception{
        Netpackage pkg = NetFormat.delFriendEncode(mUid , (int)resMap.get("uid") , mKey);
        //删除contacts列表中对应的数据
        contacts.delete_contact((int)resMap.get("uid"));
        //删除sessions列表中对应的数据
        sessions.delete_session((int)resMap.get("uid"));
        //删除数据库chat_session表数据
        DBHelperUtil.getInstance().del_session((int) resMap.get("uid"));
        _sendPackage(pkg);
    }

    //网络请求 获取联系人列表
    private void NetFriendList(Map<String , Object> resMap) throws Exception{
        //判断列表缓存是否有数据，有数据则直接返回，没有数据请求服务端初始化
        if(contacts.get_allcontacts().size() > 0){
            //序列化ContactList
            String str_contacts = GsonUtil.toJson(contacts);
            //发送给UI
            Map<String, Object> brocastMap = new HashMap<>();
            brocastMap.put("type", BroadcastMsg.DATA_CORE_CONTACTS);
            brocastMap.put("result", 0);
            brocastMap.put("msg", "");
            brocastMap.put("contacts" , str_contacts);
            BundleUtil bundleUtil = new BundleUtil(BroadcastMsg.SIG_CORE_DATA, brocastMap, null);
            BroadcastSender(bundleUtil.getBundle());
        }else{
            Netpackage pkg = NetFormat.friendListEndcode(mUid , mKey);
            _sendPackage(pkg);
        }
    }

    //网络请求 获取离线消息
    private void NetOffMessage(Map<String , Object> resMap) throws Exception{
        Netpackage pkg = NetFormat.offMessageEncode(mUid , mKey);
        _sendPackage(pkg);
    }

    //本地处理 获取最近会话列表
    private void DataSessions(Map<String , Object> resMap){
        //判断是否已经初始化过，初始化过则直接返回list，否则读取数据库
        if (!sessions.isInit()){
            List<DBSession> dbSessions = DBHelperUtil.getInstance().get_allsessions();
            if(dbSessions != null) {
                sessions.set_sessions(dbSessions);
            }
        }
        String str_sessions = GsonUtil.toJson(sessions);
        //发送给UI
        Map<String, Object> brocastMap = new HashMap<>();
        brocastMap.put("type", BroadcastMsg.DATA_CORE_SESSIONS);
        brocastMap.put("result", 0);
        brocastMap.put("msg", "");
        brocastMap.put("sessions" , str_sessions);
        BundleUtil bundleUtil = new BundleUtil(BroadcastMsg.SIG_CORE_DATA, brocastMap, null);
        BroadcastSender(bundleUtil.getBundle());
    }

    //本地处理 获取个人信息
    private void DataMyinfo(Map<String , Object> resMap){
        Map<String, Object> brocastMap = new HashMap<>();
        brocastMap.put("type", BroadcastMsg.DATA_CORE_MYINFO);
        brocastMap.put("uid", mUid);
        brocastMap.put("name", mUsername);
        brocastMap.put("headimg", mHeadimg);
        BundleUtil bundleUtil = new BundleUtil(BroadcastMsg.SIG_CORE_DATA, brocastMap, null);
        BroadcastSender(bundleUtil.getBundle());
    }

    //网络请求 下载网络图片
    private void NetDownpic(Map<String , Object> resMap){
        _getNetImage((int)resMap.get("uid") , (String) resMap.get("filename"));
    }

    //网络请求 上传图片
    private void NetUploadpic(Map<String , Object> resMap){
        _putNetImage((String) resMap.get("filename"));
    }

    //本地处理 新的朋友申请列表
    private void DataNewFriend(Map<String , Object> resMap){
        List<DBUser> users = DBHelperUtil.getInstance().get_newfrienduser();
        if(users != null){
            ContactList contactList = new ContactList();
            for (DBUser user : users){
                DBContact contact = new DBContact();
                contact.setUid(user.getUid());
                contact.setName(user.getName());
                contact.setHeadimg(user.getHeadimg());
                contact.setType(user.getType());
                contactList.insert_contact(contact);
            }
            //序列化ContactList
            String str_contactlist = GsonUtil.toJson(contactList);
            //发送给UI
            Map<String, Object> brocastMap = new HashMap<>();
            brocastMap.put("type", BroadcastMsg.DATA_CORE_NEWFRIEND);
            brocastMap.put("result", 0);
            brocastMap.put("msg", "");
            brocastMap.put("newfriends" , str_contactlist);
            BundleUtil bundleUtil = new BundleUtil(BroadcastMsg.SIG_CORE_DATA, brocastMap, null);
            BroadcastSender(bundleUtil.getBundle());
        }
    }

    //本地处理 获取聊天记录
    private void DataMessages(Map<String , Object> resMap){
        List<DBMessage> messages = DBHelperUtil.getInstance().get_msgs((int) resMap.get("uid") , (int) resMap.get("start") , (int) resMap.get("limit"));
        Map<String, Object> brocastMap = new HashMap<>();
        brocastMap.put("type", BroadcastMsg.DATA_CORE_GETMSG);
        MessageList messageList = new MessageList();
        if(messages != null){
            messageList.set_messages(messages);
        }
        //序列化MessageList
        String str_messages = GsonUtil.toJson(messageList);
        //发送给UI
        brocastMap.put("result", 0);
        brocastMap.put("msg", "");
        brocastMap.put("messages" , str_messages);
        BundleUtil bundleUtil = new BundleUtil(BroadcastMsg.SIG_CORE_DATA, brocastMap, null);
        BroadcastSender(bundleUtil.getBundle());
    }

    //本地处理 更新会话信息
    private void DataUpdateSession(Map<String , Object> resMap){
        Map<String, Object> brocastMap = new HashMap<>();
        brocastMap.put("type", BroadcastMsg.DATA_CORE_SETSESSION);
        if((int) resMap.get("uid") > 0){
            DBSession session = new DBSession();
            session.setUid((int) resMap.get("uid"));
            session.setUnread((int) resMap.get("unread"));
            //修改sessionList
            sessions.update_session(session);
            //修改数据库
            DBHelperUtil.getInstance().update_session(session);
            brocastMap.put("result", 0);
            brocastMap.put("msg", "");
        }else{
            brocastMap.put("result", 1);
            brocastMap.put("msg", "找不到该会话信息");
        }
        BundleUtil bundleUtil = new BundleUtil(BroadcastMsg.SIG_CORE_DATA, brocastMap, null);
        BroadcastSender(bundleUtil.getBundle());
    }

    //本地处理 删除聊天记录
    private void DataDeleteMsg(Map<String , Object> resMap){
        Map<String, Object> brocastMap = new HashMap<>();
        brocastMap.put("type", BroadcastMsg.DATA_CORE_DELLOG);
        if(DBHelperUtil.getInstance().clear_msg((int) resMap.get("uid"))){
            brocastMap.put("result", 0);
            brocastMap.put("msg", "");
        }else{
            brocastMap.put("result", 1);
            brocastMap.put("msg", "读写数据库失败");
        }
        BundleUtil bundleUtil = new BundleUtil(BroadcastMsg.SIG_CORE_DATA, brocastMap, null);
        BroadcastSender(bundleUtil.getBundle());
    }

    //本地处理 获取系统设置
    private void DataGetConfig(Map<String , Object> resMap){
        String key = (String) resMap.get("key");
        if (key.equals("notify")){
            Map<String, Object> brocastMap = new HashMap<>();
            brocastMap.put("type", BroadcastMsg.DATA_CORE_GETCONFIG);
            brocastMap.put("value" , AppRuntime.getIsNotify());
            BundleUtil bundleUtil = new BundleUtil(BroadcastMsg.SIG_CORE_DATA, brocastMap, null);
            BroadcastSender(bundleUtil.getBundle());
        }
    }

    //本地处理 修改系统设置
    private void DataSetConfig(Map<String , Object> resMap){
        String key = (String) resMap.get("key");
        if (key.equals("notify")){
            AppRuntime.setIsNotify((boolean) resMap.get("value"));
            SPUtil.put(mainApp.getContext() , "globle_notify" , (boolean) resMap.get("value"));
            Map<String, Object> brocastMap = new HashMap<>();
            brocastMap.put("type", BroadcastMsg.DATA_CORE_SETCONFIG);
            brocastMap.put("result" , 0);
            BundleUtil bundleUtil = new BundleUtil(BroadcastMsg.SIG_CORE_DATA, brocastMap, null);
            BroadcastSender(bundleUtil.getBundle());
        }else if(key.equals("sessionuid")){
            AppRuntime.setSessionUid((int) resMap.get("value"));
            Map<String, Object> brocastMap = new HashMap<>();
            brocastMap.put("type", BroadcastMsg.DATA_CORE_SETCONFIG);
            brocastMap.put("result" , 0);
            BundleUtil bundleUtil = new BundleUtil(BroadcastMsg.SIG_CORE_DATA, brocastMap, null);
            BroadcastSender(bundleUtil.getBundle());
        }
    }

    /**
     * TODO:将信息包发送给服务器
     * @param pkg   包信息
     * @throws IOException  抛出socket的IO错误
     */
    private void _sendPackage(Netpackage pkg) throws IOException{
        if(pkg != null) {
            byte msgData[] = pkg.getByte();
            mSocket.send(msgData, msgData.length);
        }
    }

    /**
     TODO：下载文件函数，该函数是异步调用的
     @param  from 文件归属用户id
     @param  filename 存放于getExternalFilesDir的uid目录下的文件名
     */
    private void _getNetImage(int from , String filename){
        //设置cookies
        String cookies = "uid=" + String.valueOf(mUid) + "; key=" + mKey + ";";

        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder()
                .add("from" , String.valueOf(from))
                .add("file", filename)
                .build();
        Request request = new Request.Builder()
                .url(AppRuntime.getFileHost() + "/download.php")
                .header("Cookie", cookies)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Logger.d("GetNetImage" + e.getMessage());
                Map<String, Object> brocastMap = new HashMap<>();
                brocastMap.put("type", BroadcastMsg.DATA_CORE_DOWNPIC);
                brocastMap.put("result", 1);
                brocastMap.put("msg" , e.getMessage());
                BundleUtil bundleUtil = new BundleUtil(BroadcastMsg.SIG_CORE_DATA, brocastMap, null);
                BroadcastSender(bundleUtil.getBundle());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Headers headers = response.headers();
                boolean isFile = false;
                for (int i = 0; i < headers.size(); i++) {
                    Log.d("download", headers.name(i) + ":" + headers.value(i));
                    if(headers.name(i).equalsIgnoreCase("Content-Type")){
                        if(headers.value(i).indexOf("application/octet-stream") >= 0){
                            isFile = true; }
                    }
                }
                byte resByte[] = response.body().bytes();
                Map<String, Object> brocastMap = new HashMap<>();
                if(isFile){
                    FileUtil.writeToPrivate(mainApp.getContext() , filename , String.valueOf(mUid), resByte);
                    brocastMap.put("type", BroadcastMsg.DATA_CORE_DOWNPIC);
                    brocastMap.put("result", 0);
                    brocastMap.put("msg" , "");
                    brocastMap.put("filename", filename);
                }else{
                    //异步通知主线程发生错误
                    brocastMap.put("type", BroadcastMsg.DATA_CORE_DOWNPIC);
                    brocastMap.put("result", 2);
                    brocastMap.put("msg" , "file data error");
                    brocastMap.put("filename", filename);
                }
                BundleUtil bundleUtil = new BundleUtil(BroadcastMsg.SIG_CORE_DATA, brocastMap, null);
                BroadcastSender(bundleUtil.getBundle());
            }
        });
    }

    /**
     TODO：上传文件函数，该函数是异步调用的
     @param  filename 存放于getExternalFilesDir的uid目录下的文件名
     */
    private void _putNetImage( String filename){
        File file= new File(mainApp.getContext().getExternalFilesDir(String.valueOf(mUid)) , filename);
        if (file.getName() == null){
            BundleUtil bundleUtil = new BundleUtil(BroadcastMsg.SIG_CORE_SYSERR , "找不到文件");
            BroadcastSender(bundleUtil.getBundle());
            return;
        }
        //设置cookies
        String cookies = "uid=" + String.valueOf(mUid) + "; key=" + mKey + ";";

        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", filename, RequestBody.create(MediaType.parse("application/octet-stream"), file))
                .build();

        Request request = new Request.Builder()
                .url(mainApp.getFileServer() + "/upload.php")
                .header("Cookie", cookies)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Logger.d("PutNetImage" + e.getMessage());
                Map<String, Object> brocastMap = new HashMap<>();
                brocastMap.put("type", BroadcastMsg.DATA_CORE_UPLOADPIC);
                brocastMap.put("result", 1);
                brocastMap.put("msg" , e.getMessage());
                brocastMap.put("filename" , "");
                BundleUtil bundleUtil = new BundleUtil(BroadcastMsg.SIG_CORE_DATA, brocastMap, null);
                BroadcastSender(bundleUtil.getBundle());
            }

            @Override
            public void onResponse(Call call, Response response){
                //发送上传成功消息给UI
                Map<String, Object> brocastMap = new HashMap<>();
                brocastMap.put("type", BroadcastMsg.DATA_CORE_UPLOADPIC);
                brocastMap.put("result", 0);
                brocastMap.put("msg" , "");
                brocastMap.put("filename" , filename);
                BundleUtil bundleUtil = new BundleUtil(BroadcastMsg.SIG_CORE_DATA, brocastMap, null);
                BroadcastSender(bundleUtil.getBundle());
            }
        });
    }
}
